<template>
  <div class="about">
    <button @click="$router.push('/shopcar')">跳转购物车</button>
    <el-button type="primary" @click="sortA">价格从高到低</el-button>
    <el-button type="primary" @click="sortB">价格从低到高</el-button>
    <ul class="con">
      <li v-for="item in list" :key="item.spuInfo.spuId">
        <img :src="item.spuInfo.images" alt="" />
        <h5>{{ item.spuInfo.spuTitle }}</h5>
        <p>{{ item.spuInfo.spuSubTitle }}</p>
        <h6>{{ item.spuInfo.price }}</h6>
        <el-button type="primary" size="mini" @click="add(item.spuInfo)"
          >加入购物车</el-button
        >
        <el-button
          size="mini"
          @click="$router.push('/detail/' + item.spuInfo.spuId)"
          >查看详情</el-button
        >
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [],
    };
  },
  methods: {
    getList() {
      this.$axios.get("goodsList.json").then((res) => {
        console.log(res);
        this.list = res.data.data.list;
      });
    },
    sortA() {
      this.list.sort((a, b) => {
        return b.spuInfo.price - a.spuInfo.price;
      });
      //sort 会改变原数组
    },
    sortB() {
      this.list.sort((a, b) => {
        return a.spuInfo.price - b.spuInfo.price;
      });
      //sort 会改变原数组
    },
    add(val) {
      if (localStorage.getItem("token")) {
        this.$store.commit("add", val);
      } else {
        this.$message({
          type: "error", // success error warning
          message: "没有登陆不能加入购物车",
        });
      }
    },
    //加入购物车的方法
  },
  created() {
    this.getList();
  },
};
</script>
<style lang="scss">
.con {
  width: 1000px;
  margin: 50px auto;
  display: flex;
  flex-wrap: wrap;

  li {
    width: 20%;
    border: 1px solid #ccc;
    box-sizing: border-box;
    img {
      width: 80%;
    }
    > h5,
    > p {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
</style>
